﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Metro;
using DevComponents.DotNetBar.SuperGrid;
using Platform.Model;
using Platform.Model.Repositories;
using System.Globalization;
using BLToolkit.Data.Sql;

namespace PlatformManagement
{

    public partial class StoreForm : MetroForm
    {
        bool isValitadeToInsert = false;
        public StoreForm()
        {
            InitializeComponent();
            sgStore.PrimaryGrid.AutoGenerateColumns = false;
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            this.WindowState = FormWindowState.Maximized;
        }

        private void StoreForm_Load(object sender, EventArgs e)
        {
            LoadSuperGrid();
        }

        public void LoadSuperGrid()
        {


            sgStore.PrimaryGrid.DataSource = new BindingSource { DataSource = WorkContext.Current.Storages.ToList() };

        }





        private void GetDataFromSuperGrid(Store store, GridRowValidatedEventArgs e)
        {
            if (e.GridRow.Cells[2].Value != null)
                store.StoreNo = e.GridRow.Cells[2].Value.ToString();
            if (e.GridRow.Cells[3].Value != null)
                store.StoreName = e.GridRow.Cells[3].Value.ToString();
            if (e.GridRow.Cells[4].Value != null)
                store.Address = e.GridRow.Cells[4].Value.ToString();
            store.LastUpdated = DateTime.Now;
        }



        /// <summary>
        /// ** Kiem tra du lieu khi edit row
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sgStore_RowValidating(object sender, GridRowValidatingEventArgs e)
        {

            //** Nếu cột id = null => insert store => kiem tra du lieu nhap co null ko
            if (e.GridRow.Cells[1].Value == null || Int32.Parse(e.GridRow.Cells[1].Value.ToString()) == 0)
            {
                // Truong hop nhap du lieu ko day du
                if (e.GridRow[2].Value == null || e.GridRow[3].Value == null)
                {
                    MessageBox.Show("You have to enter value for all cells");
                    isValitadeToInsert = false;
                    sgStore.PrimaryGrid.Rows.Remove(e.GridRow);
                    return;
                }
                else
                {
                    isValitadeToInsert = true;
                }
            }

        }
        /// <summary>
        /// ** xử lý insert/update
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sgStore_RowValidated(object sender, GridRowValidatedEventArgs e)
        {
            //neu checkbox duoc check: xoa dong ==> return => goi su kien btnDelete_Click
            if (e.GridRow.Cells[0].Value != null)
            {
                bool isCheckedRow = (bool)e.GridRow.Cells[0].Value;

                if (isCheckedRow)
                {
                    return;
                }
            }


            Store store;

            //** Nếu cột id = null => insert store
            if (e.GridRow.Cells[1].Value == null || Int32.Parse(e.GridRow.Cells[1].Value.ToString()) == 0)
            {
                if (isValitadeToInsert)
                {
                    //** Tạo một đối tượng Store mới
                    store = new Store();

                    try
                    {
                        //** Lấy dữ liệu từ SuperGrid đổ vào đối tượng
                        GetDataFromSuperGrid(store, e);
                        store.MarketId = WorkSession.Current.Market.ID;
                        //Chèn vào CSDL store mới
                        int id = StoreRepository.Insert(store);
                        // Gan lai id cua mat hang vao cot thu 2 cua grid
                        e.GridRow.Cells[1].Value = id;
                    }
                    catch (DuplicateNameException ex)
                    {
                        MessageBox.Show(ex.Message, "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        sgStore.PrimaryGrid.Rows.Remove(e.GridRow);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Insert Failed!", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        sgStore.PrimaryGrid.Rows.Remove(e.GridRow);
                    }

                }

            }
            else //** Nếu cột id != null => update store
            {
                //** Lấy Id từ cột Id
                int id = Int32.Parse(e.GridRow.Cells[1].Value.ToString());

                //** Lấy store theo id
                store = StoreRepository.GetById(id);

                //** Lấy dữ liệu mới từ SuperGrid đổ vào đối tượng
                GetDataFromSuperGrid(store, e);

                //** Cập nhật store lưu vào CSDL 
                StoreRepository.Update(store);
            }
        }



        private void btnDelete_Click(object sender, EventArgs e)
        {
            var message = "All selected stores and related data will be deleted forever. Are you sure?";

            // Xuat thong bao yeu cau nguoi dung xac nhan viec xoa
            if (MessageBox.Show(message, "Warning !!!", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                // Lay tat ca cac dong
                var rows = sgStore.PrimaryGrid.Rows;

                GridRow gRow;
                Store store;
                bool isCheckedRow;

                try
                {
                    // duyet qua tung dong
                    for (int i = rows.Count - 2; i >= 0; i--)
                    {
                        gRow = (GridRow)rows[i];

                        if (gRow.Cells[0].Value != null)
                        {
                            isCheckedRow = (bool)gRow.Cells[0].Value;

                            //Kiem tra checkbox co duoc check?
                            if (isCheckedRow)
                            {
                                // Lay ra mat hang duoc chon
                                store = gRow.DataItem as Store;

                                // Goi ham xoa mat hang & xoa dong duoc chon
                                StoreRepository.Delete(store);
                                sgStore.PrimaryGrid.Rows.Remove(gRow);
                                WorkContext.Current.Storages.ToList().Remove(store);

                            }
                        }


                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message, "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception)
                {
                    MessageBox.Show("Delete Failed!", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

    }
}